﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using BookTheBook.Data.Model;
using NHibernate;

namespace BookTheBook.Data
{
    public class NHibernateBookEntitiesDbCommunicator : IBookEntitiesDbCommunicator
    {
        private static Database _db = new Database();

        public void SubmitBooksToDataSource(IEnumerable<Book> books)
        {
            ISession session = _db.Session;
            using (var transaction = session.BeginTransaction())
            {
                foreach (Book book in books)
                {
                    if (!book.Author.Contains(","))
                    session.SaveOrUpdate(book);
                }
                transaction.Commit();
            }
        }

        public ReadOnlyCollection<Book> GetAllBooks()
        {
            ISession session = _db.Session;
            IList<Book> allBooks = new List<Book>();
            using (session.BeginTransaction())
            {
                allBooks = session.CreateCriteria(typeof (Book)).List<Book>();
            }
            return new ReadOnlyCollection<Book>(allBooks);
        }

        public Book GetBookById(int id)
        {
            ISession session = _db.Session;
            IList<Book> allBooks = new List<Book>();
            using (session.BeginTransaction())
            {
                allBooks = session.CreateCriteria(typeof(Book)).List<Book>();
            }
            foreach (Book book in allBooks)
            {
                if (book.Id == id)
                    return book;
            }
            return null;
        }
    }
}